package servlets;

import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ejbSessions.ManagerUtenteRemote;
import ejbSessions.ManagerAbilitaRemote;
import EJBPackage.Utente;

/**
 * Servlet implementation class CreaRichiestaAiuto
 */
public class CreaRichiestaAiuto extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreaRichiestaAiuto() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		gestisciRichiesta(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		gestisciRichiesta(request,response);
	}
	
	private void gestisciRichiesta(HttpServletRequest request, HttpServletResponse response){
		int idUtente, idDestinatario;
		String descrizione;
		RequestDispatcher dispatcher = request.getRequestDispatcher("/CreaRichiestaAiuto.jsp");
		HttpSession session = request.getSession();
		try{
			Hashtable<String,String> env = new Hashtable<String,String>();
			env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL,"localhost:1099");
			InitialContext jndiContext = new InitialContext(env);
			Object ref = jndiContext.lookup("ManagerUtente/remote");
			ManagerUtenteRemote manager = (ManagerUtenteRemote)ref;
			Object ref2 = jndiContext.lookup("ManagerAbilita/remote");
			ManagerAbilitaRemote managerAbilita = (ManagerAbilitaRemote)ref2;
			
			idDestinatario = Integer.parseInt((String) request.getParameter("utente"));
			Utente destinatario = manager.getUtente(idDestinatario);
			session.setAttribute("idDestinatario", idDestinatario);
			session.setAttribute("nomeDestinatario", destinatario.getNome()+" "+destinatario.getCognome());
			session.setAttribute("abilita", destinatario.getAbilita());
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		try {
			dispatcher.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
